package com.bacon.gmall.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author： bacon、
 * @version： 1.0
 * @create： 2021-01-04 18:22
 * @description: 拦截器
 *
 */
public class FeignInterceptor implements RequestInterceptor {


    //拦截器方法  RequestTemplate：远程调用请求对象
    @Override
    public void apply(RequestTemplate requestTemplate) {

        //1、当前请求对象头中用户ID  传递给  远程调用请求对象的头中
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (null != requestAttributes){
            //当前微服务的请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            if (null != request) {
                //网关传递过来的真实用户ID
                String userId = request.getHeader("userId");
                if (!StringUtils.isEmpty(userId)) {
                    requestTemplate.header("userId",userId);
                }

                //网关传递过来的临时用户ID
                String userTempId = request.getHeader("userTempId");
                if (!StringUtils.isEmpty(userTempId)){
                    requestTemplate.header("userTempId",userTempId);
                }
            }
        }
    }
}
